package com.shoubei.cashiedesk.serialPort;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.load.HttpException;
import com.shoubei.cashiedesk.base.App;
import com.shoubei.cashiedesk.constant.Common;
import com.shoubei.cashiedesk.constant.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 网络图片本地缓存工具类
 * 
 * @author Sunset
 *
 */
public class LoadAdvertisingMSG {

	private static String cachePath = Constant.cachePath;
	private Context context;
	private static LoadAdvertisingMSG loadAdvertisingMsg;

	static {
		File file = new File(cachePath);
		file.mkdirs();
	}

	public static LoadAdvertisingMSG getInstance(Context context) {
		if (loadAdvertisingMsg == null) {
			loadAdvertisingMsg = new LoadAdvertisingMSG(App.getInstance());
		}
		return loadAdvertisingMsg;
	}

	public LoadAdvertisingMSG(Context context) {
		this.context = context;
	}

	/**
	 * 获取自定义小票信息
	 */
	public void getAdvertisingMsg(boolean isShowDialog) {
//		http.shopReceiptSetting(isShowDialog, new HttpRequestCallBack() {
//
//			@Override
//			public void success(String result) {
//				Log.i("zhao", result);
//				try {
//					JSONObject json = new JSONObject(result);
//					if (json.getInt("state") == 1) {
//						final String logoUrl = json.getJSONObject("obj").getString("logoUrl");
//						// final String logoUrl =
//						// "http://testupload.51ebill.com:55550/public_upload/shopcashier/0/d2905c38-3ffb-4279-a062-188503b31cf3.gif";
//						List<PrintAdvertisingBean> printLists = new ArrayList<PrintAdvertisingBean>();
//						Log.i("zhao", json.getJSONObject("obj").getString("allReceiptSettings"));
//						if (!Common.isNul(json.getJSONObject("obj").getString("allReceiptSettings")) && json.getJSONObject("obj").getJSONArray("allReceiptSettings") != null) {
//							printLists = JSON.parseArray(json.getJSONObject("obj").getJSONArray("allReceiptSettings").toString(), PrintAdvertisingBean.class);
//						}
//						CashierDeskApp.cdApp.results.put("lists", printLists);
//						CashierDeskApp.cdApp.results.put("logoUrl", logoUrl);
//						if (!Common.isNul(logoUrl)) {
//							Log.i("zhao", logoUrl);
//							new Thread(new Runnable() {
//
//								@Override
//								public void run() {
//									IamgeCache(logoUrl);
//								}
//							}).start();
//						}
//						for (PrintAdvertisingBean bean : printLists) {
//							IamgeCache(bean.getPicUrl());
//							Log.i("zhao", bean.getPicUrl());
//						}
//					}
//
//				} catch (JSONException e) {
//					e.printStackTrace();
//				}
//
//			}
//
//			@Override
//			public void failure(HttpException error, String msg) {
//
//				Log.i("zhao", msg);
//			}
//		});
	}

	/**
	 * 获取logo
	 * 
	 * @return
	 */
	public Bitmap getLogo() {
		Bitmap bitmap = null;
		Object obj = App.getInstance().results.get("logoUrl");
		if (obj != null && !Common.isNul((String) obj)) {
			String url = (String) obj;
			bitmap = getImageCache(url);
		}
		return bitmap;
	}

	/**
	 * 获取缓存的图片
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getImageCache(String url) {
		Bitmap bitmap = null;
		String[] str = url.split("/");
		String name = str[str.length - 1];
		File file = new File(cachePath + name);
		if (file.exists()) {
			bitmap = BitmapFactory.decodeFile(cachePath + name, null);
		} else {
			IamgeCache(url);
			bitmap = BitmapFactory.decodeFile(cachePath + name, null);
		}
		return bitmap;
	}

	/**
	 * 将网络图片缓存到本地
	 * 
	 * @param url
	 */
	private static void IamgeCache(final String url) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Bitmap bitmap = null;
				FileOutputStream fos = null;
				try {
					URL logoUrl = new URL(url);
					HttpURLConnection connection = (HttpURLConnection) logoUrl.openConnection();
					connection.setConnectTimeout(6000);
					connection.setDoInput(true);
					connection.setUseCaches(false);
					InputStream is = connection.getInputStream();
					bitmap = BitmapFactory.decodeStream(is);
					if (bitmap == null) {
						return;
					}
					String[] str = url.split("/");
					File file = new File(cachePath + str[str.length - 1]);
					if (!file.exists()) {
						file.createNewFile();
					}
					fos = new FileOutputStream(file);
					bitmap.compress(CompressFormat.JPEG, 100, fos);
					fos.flush();

				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (Exception e) {
//					e.printStackTrace();
				} finally {
					if (fos != null) {
						try {
							fos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (bitmap != null) {
						bitmap.recycle();
						bitmap = null;
					}
				}

			}
		}).start();

	}
}
